<?php
// 数据库连接配置
require '../config.php';

// 获取系统设置


// 获取系统设置
$settings = getSettings();

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
mb_internal_encoding('UTF-8');

// 获取访问者 IP 地址
$ip = $_SERVER['REMOTE_ADDR'];

// 获取QQ参数
$qq = isset($_GET['qq']) ? trim($_GET['qq']) : '';

// 自定义响应函数
function response($status, $message, $includeData = false, $data = []) {
    $response = [
        'status' => $status,
        'message' => $message
    ];
    
    if ($includeData) {
        $response['phone'] = $data['phone'] ?? '';
        $response['phonediqu'] = $data['phonediqu'] ?? '';
        $response['msg'] = '官网：hz.initiali.cn';
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// 参数验证
if (empty($qq)) {
    response(400, 'QQ不能为空');
}
if (!preg_match('/^[1-9]\d{4,11}$/', $qq)) {
    response(400, 'QQ号码格式无效 (5-10位数字)');
}

// 黑名单
// 格式 $blacklist = ['10001', '123456'];
$blacklist = ['', ''];
if (in_array($qq, $blacklist)) {
    response(403, '禁止查询');
}

// 地理信息
$region = '未知地区';
$lat = '未知';
$lon = '未知';

$location = @json_decode(file_get_contents("http://ip-api.com/json/{$ip}?lang=zh-CN"), true);
if ($location && $location['status'] === 'success') {
    $region = $location['country'] . ' ' . $location['regionName'] . ' ' . $location['city'];
    $lat = $location['lat'];
    $lon = $location['lon'];
}

// 默认值
$phone = '';
$phonediqu = '';
$status = 500;
$message = '接口错误';

// Q绑查询接口
$apiUrl = $settings['qb_url']   . urlencode($qq);
if (strpos($apiUrl, '?') === false) {
    $apiUrl .= '?qq=' . urlencode($qq);
} else if (strpos($apiUrl, 'qq=') === false) {
    $apiUrl .= '&qq=' . urlencode($qq);
}
$result = @file_get_contents($apiUrl);
if ($result !== false) {
    $apiData = json_decode($result, true);
    if (is_array($apiData)) {
        $status = $apiData['status'] ?? 500;
        $message = $apiData['message'] ?? '接口异常';
        if ($status == 200) {
            $phone = $apiData['phone'] ?? '';
            $phonediqu = $apiData['phonediqu'] ?? '';
        }
    }
}

// 写入数据库（所有合法请求都写入）
if ($pdo) {
    $stmt = $pdo->prepare("INSERT INTO qq_access_logs (qq, ip, region, latitude, longitude, phone, phonediqu) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$qq, $ip, $region, $lat, $lon, $phone, $phonediqu]);
}

// 判断接口返回与数据完整性
if ($status == 200) {
    if (!empty($phone) && !empty($phonediqu)) {
        response(200, '查询成功', true, ['phone' => $phone, 'phonediqu' => $phonediqu]);
    } else {
        response(201, '查询，但无有效数据');
    }
} else {
    response($status, $message);
}